package com.pn.warehouse.service.impl;

import com.pn.warehouse.dto.AssignAuthDto;
import com.pn.warehouse.entity.Result;
import com.pn.warehouse.entity.Role;
import com.pn.warehouse.entity.RoleAuth;
import com.pn.warehouse.mapper.AuthMapper;
import com.pn.warehouse.mapper.RoleAuthMapper;
import com.pn.warehouse.mapper.RoleMapper;
import com.pn.warehouse.page.Page;
import com.pn.warehouse.service.RoleService;
import com.pn.warehouse.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

import javax.annotation.Resource;
import java.util.List;

//指定缓存的名称（数据库保存到redis中的键的前缀，一般填累的全路径）
@CacheConfig(cacheNames = "com.pn.warehouse.service.impl.RoleServiceImpl")
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleAuthMapper roleAuthMapper;

    @Resource
    private AuthMapper authMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //查询所有的角色
    @Cacheable(key = "'all:role'") //指定缓存的键，存的是返回结果
    @Override
    public List<Role> queryAllRole() {
        List<Role> allRole = roleMapper.findAllRole();
        return allRole;
    }

    //根据用户id查询用户分配的所有角色
    @Override
    public List<Role> queryUserRoleByUid(Integer userId) {
        List<Role> roleList = roleMapper.findUserRoleByUid(userId);
        return roleList;
    }

    //分页查询角色信息
    @Override
    public Page queryRolePage(Page page, Role role) {
        //1、查询角色的行数
        Integer rowCount = roleMapper.findRoleRowCount(role);
        //2、分页查询角色信息
        List<Role> roleList = roleMapper.findRolePage(page, role);
        //3、赋值给page对象并返回
        page.setTotalNum(rowCount);
        page.setResultList(roleList);
        return page;
    }

    //新增角色
    @CacheEvict(key = "'all:role'") //增加角色要删除缓存
    @Override
    public Result insertRole(Role role) {
        //1、判断该角色是否存在（包括角色名字和角色代码）
        Role role1 = roleMapper.findRoleByNameOrCode(role.getRoleName(), role.getRoleCode());
        if (role1 != null){
            return Result.err(Result.CODE_ERR_BUSINESS, "该角色已经存在！");
        }

        //2、添加角色
        int i = roleMapper.insertRole(role);
        if (i > 0){
            return Result.ok("添加角色成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "添加角色失败！");
    }

    //根据id更新角色的状态
    @CacheEvict(key = "'all:role'") //修改角色要删除缓存
    @Override
    public Result updateRoleStateById(Role role) {
        int i = roleMapper.updateRoleStateById(role);
        if (i > 0){
            return Result.ok("修改状态成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "修改状态失败！");
    }

    //根据id删除角色
    @CacheEvict(key = "'all:role'")
    @Override
    public Result removeRoleById(Integer roleId) {
        //1、删除角色信息
        int i = roleMapper.removeRoleById(roleId);
        if (i > 0){
            //2、删除角色权限关联信息
            roleAuthMapper.removeRoleAuthById(roleId);
            return Result.ok("删除角色成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "删除角色失败！");
    }

    //查询角色分配的所有权限
    @Override
    public List<Integer> findAuthIdsById(Integer roleId) {
        List<Integer> authIdsById = roleAuthMapper.findAuthIdsById(roleId);
        return authIdsById;
    }

    //添加角色权限关系
    @Transactional
    @Override
    public void insertRoleAuth(AssignAuthDto assignAuthDto, Integer userId) {
        //1、删除角色之前所分配的权限
        roleAuthMapper.removeRoleAuthById(assignAuthDto.getRoleId());

        //2、添加新的角色权限关系
        List<Integer> authIds = assignAuthDto.getAuthIds();
        for (Integer authId : authIds) {
            RoleAuth roleAuth = new RoleAuth();
            roleAuth.setRoleId(assignAuthDto.getRoleId());
            roleAuth.setAuthId(authId);
            roleAuthMapper.insertRoleAuth(roleAuth);
        }

        //3、清除缓存
        redisTemplate.delete("authTree" + userId);
    }

    //根据角色id修改角色描述
    @CacheEvict(key = "'all:role'")
    @Override
    public Result updateDescById(Role role) {
        int i = roleMapper.updateDescById(role);
        if (i > 0){
            return Result.ok("修改角色描述成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "修改角色描述失败！");
    }

}
